package com.lzw.bluetoothpractice.Activitys;

import androidx.appcompat.app.AppCompatActivity;


import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.lzw.bluetoothpractice.AppConfig;
import com.lzw.bluetoothpractice.Fragment.ShouyeFragment;
import com.lzw.bluetoothpractice.Models._User;
import com.lzw.bluetoothpractice.R;
import com.lzw.bluetoothpractice.Utils.AppUtil;
import com.lzw.bluetoothpractice.Utils.MD5Utils;
import com.lzw.bluetoothpractice.Utils.SharePreferenceUtils;
import com.lzw.bluetoothpractice.bean.LoginBody;
import com.lzw.bluetoothpractice.bean.RecommendDoctorBean;
import com.lzw.bluetoothpractice.bean.SystemUserBean;
import com.lzw.bluetoothpractice.network.HeadAssmblyUtils;
import com.lzw.bluetoothpractice.network.RetrofitManager;
import com.lzw.bluetoothpractice.network.api.RequestApi;

import java.util.Map;
import java.util.logging.Logger;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;


import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.lzw.bluetoothpractice.MyApplication.getContext;


public class LoginActivity extends AppCompatActivity implements View.OnClickListener{

    // 登录按钮
    private Button login, register,error;
    // 电话号码输入框
    private EditText telephone;
    // 密码输入框
    private EditText password;
    public String login_tele, login_pass;
    private CheckBox checkBox;

    SharedPreferences sp;// 通过sp对象对/data/data/sharedPerences/目录下的.xml进行读写
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);


        init();
        sp = this.getSharedPreferences("user1", Context.MODE_PRIVATE);
        telephone.setText(sp.getString("telephone", ""));
        password.setText(sp.getString("password", ""));
        login.setOnClickListener(this);
        register.setOnClickListener(this);
        error.setOnClickListener(this);
        checkBox.setOnClickListener(this);
    }

    private void init() {
        login = (Button) this.findViewById(R.id.bt_login);
        register = (Button) this.findViewById(R.id.register);
        telephone = (EditText) this.findViewById(R.id.et_telephone);
        password = (EditText) this.findViewById(R.id.et_password);
        error = (Button) this.findViewById(R.id.error1);
        checkBox = (CheckBox)this.findViewById(R.id.checkbox);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.bt_login:
                checklogin();     //登陆的方法
                break;
            case R.id.register:   //进行注册
                Intent intent1 = new Intent(LoginActivity.this,RegisterActivity.class);
                startActivity(intent1);
                break;
            case R.id.error1:  //进行短信登录
                Intent intent = new Intent(LoginActivity.this, SMSLoginActivity.class);
                startActivity(intent);
                break;
            case R.id.checkbox:
                if(checkBox.isChecked()){
                    //将Button设置为启用状态
                    login.setEnabled(true);
                    //设置TextView呈现的内容
                    checkBox.setText("您已完整阅读该协议并且同意");
                    checkBox.setTextColor(Color.rgb(189, 252, 201));
                }else{
                    //将button设置为不可启用状态
                    checkBox.setText("我同意此《用户协议和隐私政策》");
                    checkBox.setTextColor(Color.rgb(220, 220, 220));
                    login.setEnabled(false);
                }
                break;
        }
    }
    private Map<String, String> keyMap;
    // 检查登录信息
    private void checklogin() {
        if(checkBox.isChecked()){
            try {
                keyMap = HeadAssmblyUtils.HeadAssembly("/android/user/login");
            } catch (Exception e) {
                e.printStackTrace();
            }
            JSONObject jsonParams = new JSONObject();//服务器需要传参的json对象getMD5ofStrByCharset
            LoginBody loginBody=new LoginBody();
            loginBody.setUsername( telephone.getText().toString());
            loginBody.setPassword(password.getText().toString());
           // jsonParams.put("UserPhone", telephone.getText().toString());
         //   jsonParams.put("Password", );

            String accessToken = null;

            RetrofitManager.getInstance(AppConfig.BASE_URL)
                    .createReq(RequestApi.class).getcode("1", AppUtil.getVersionCode() + "", accessToken, keyMap.get("gmtStr"), keyMap.get("contentMD5"), keyMap.get("hmacCode")).
                    observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {

                    Log.e("登录",e.getMessage()+"");

                }

                @Override
                public void onNext(JSONObject json) {
                    SharePreferenceUtils.putString(getContext(), "uuid", json.getString("uuid"));
                    loginBody.setCode(json.getString("captcha"));
                    loginBody.setUuid(json.getString("uuid"));
                    RetrofitManager.getInstance(AppConfig.BASE_URL)
                            .createReq(RequestApi.class).accountLogin(loginBody, "1", AppUtil.getVersionCode() + "", accessToken, keyMap.get("gmtStr"), keyMap.get("contentMD5"), keyMap.get("hmacCode")).
                            observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {

                            Log.e("登录",e.getMessage()+"");

                        }

                        @Override
                        public void onNext(JSONObject json) {
                            int code=(int)json.getInteger("code");
                            if(code==200){
                                String token=json.getString("token");
                                Log.e("token",token);
                                SharePreferenceUtils.putString(getContext(), "access_token", token);
                                RetrofitManager.getInstance(AppConfig.BASE_URL)
                                        .createReq(RequestApi.class).getUser("1", AppUtil.getVersionCode() + "", token, keyMap.get("gmtStr"), keyMap.get("contentMD5"), keyMap.get("hmacCode")).
                                        observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
                                    @Override
                                    public void onCompleted() {

                                    }

                                    @Override
                                    public void onError(Throwable e) {

                                        Log.e("登录",e.getMessage()+"");

                                    }

                                    @Override
                                    public void onNext(JSONObject json) {

                                        SystemUserBean systemUserBean = JSON.parseObject(json.toString(), SystemUserBean.class);

                                        SharePreferenceUtils.putString(getContext(), "userId", systemUserBean.getUser().getUserId()+"");

                                        SharePreferenceUtils.putString(getContext(), "Avatar", systemUserBean.getUser().getAvatar()+"");

                                        SharePreferenceUtils.putString(getContext(), "username", systemUserBean.getUser().getNickName()+"");

                                        SharePreferenceUtils.putString(getContext(), "phone", systemUserBean.getUser().getPhonenumber()+"");

                                    }
                                });
                                //ProgressDialogUtils.dismissLoadingProgress();
                                Intent intent = new Intent(LoginActivity.this, IndexActivity.class);
                                startActivity(intent);
                            }else {
                                Toast toast=Toast.makeText(LoginActivity.this,json.get("msg")+"",Toast.LENGTH_LONG);
                                toast.show();
                            }




                        }
                    });


                    //ProgressDialogUtils.dismissLoadingProgress();

                }
            });


         
        }else{
            Toast.makeText(LoginActivity.this, "请同意此《用户协议和隐私政策》", Toast.LENGTH_SHORT).show();
        }

    }
}
